import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import '../../utils/kudo_helper.dart';
import '../../utils/image_resource_helper.dart';
import '../../widget/report_dialog.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_entity.dart';
import '../../state/weather/weather_controller.dart';
import '../../state/moment/kite_moment_controller.dart';
import '../../state/moment/kite_moment_entity.dart';
import '../../router/app_navigation_manager.dart';

/// 主页面 - 使用非常规类名避免重复
class DwellingScreen extends StatefulWidget {
  const DwellingScreen({super.key});

  @override
  State<DwellingScreen> createState() => _DwellingScreenState();
}

class _DwellingScreenState extends State<DwellingScreen> {
  @override
  void initState() {
    super.initState();
    // 初始化天气数据
    WeatherController.globalInstance.getRandomWeather();
    // 初始化Kite Moment数据
    KiteMomentController.globalInstance.getAllKiteMoments();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/main_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            // 顶部固定导航栏
            _buildFixedNavigationBar(),
            // 可滚动内容区域
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户欢迎区域
                    _buildUserWelcomeSection(),
                    // 天气显示区域
                    _buildWeatherDisplaySection().paddingTop(12.h),
                    // 功能按钮区域
                    _buildFunctionButtonsSection().paddingTop(20.h),
                    // Kite Moment列表区域
                    _buildKiteMomentSection()
                        .paddingTop(20.h)
                        .paddingBottom(120.h),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建顶部固定导航栏
  Widget _buildFixedNavigationBar() {
    return [
          // 左侧标题
          Text('Kudos')
              .fontSize(36.sp)
              .fontWeight(FontWeight.w900)
              .fontFamily(
                GoogleFonts.montserrat(fontWeight: FontWeight.w900).fontFamily,
              )
              .textColor(KudoColors.black)
              .textShadow(
                color: KudoColors.yellow,
                blurRadius: 0,
                offset: const Offset(0, 4),
              ),
          // 右侧编辑图标
          ImageResourceHelper.buildSvgIcon(
            svgPath: 'assets/svg/edit.svg',
            width: 32.w,
            height: 32.w,
            color: KudoColors.black,
          ).inkWell(onTap: () => _handleEditButtonTap()),
        ]
        .toRow(mainAxisAlignment: MainAxisAlignment.spaceBetween)
        .paddingHorizontal(16.w)
        .paddingVertical(12.h)
        .safeArea(bottom: false);
  }

  /// 构建用户欢迎区域
  Widget _buildUserWelcomeSection() {
    return PersonaSessionController.globalInstance.currentPersonaState
                .reactiveValue(context) !=
            null
        ? _buildLoggedInWelcome()
        : _buildLoggedOutWelcome();
  }

  /// 构建已登录用户欢迎区域
  Widget _buildLoggedInWelcome() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser == null) return const SizedBox.shrink();

    return [
      // 用户头像
      ImageResourceHelper.buildCircularAvatar(
        imagePath: currentUser.avatarResourceUrl,
        radius: 22.r,
        errorWidget: Icon(Icons.person, size: 22.r),
      ),
      // 欢迎文字
      Text('Hi, ${currentUser.displayAlias}, Welcome To Kudos')
          .fontSize(16.sp)
          .fontWeight(FontWeight.w900)
          .textColor(KudoColors.black)
          .fontFamily(GoogleFonts.lato().fontFamily)
          .expanded(),
    ].toRowSpace(space: 12.w).paddingHorizontal(16.w);
  }

  /// 构建未登录用户欢迎区域
  Widget _buildLoggedOutWelcome() {
    return [
          // 默认头像占位符
          CircleAvatar(
            radius: 24.r,
            backgroundColor: Colors.grey.shade300,
            child: Icon(Icons.person, size: 24.r, color: Colors.grey.shade600),
          ),
          // 欢迎文字
          Text('Hi, Guest, Welcome To Kudos')
              .fontSize(16.sp)
              .fontWeight(FontWeight.w900)
              .textColor(KudoColors.black)
              .fontFamily(GoogleFonts.lato().fontFamily)
              .expanded(),
        ]
        .toRowSpace(space: 12.w)
        .paddingHorizontal(16.w)
        .inkWell(
          onTap: () => AppNavigationManager.navigateToCredentialEntry(context),
        );
  }

  /// 构建天气显示区域
  Widget _buildWeatherDisplaySection() {
    return WeatherController.globalInstance.currentWeatherState.reactiveValue(
              context,
            ) !=
            null
        ? ImageResourceHelper.buildContainerImage(
              imagePath:
                  WeatherController
                      .globalInstance
                      .currentWeatherState
                      .value!
                      .weatherImagePath,
              width: double.infinity,
              height: 86.h,
              fit: BoxFit.fill,
              borderRadius: BorderRadius.circular(12.r),
            )
            .parent(
              ({required Widget child}) =>
                  AspectRatio(aspectRatio: 343 / 86, child: child),
            )
            .paddingHorizontal(16.w)
        : Container(
          margin: EdgeInsets.symmetric(horizontal: 16.w),
          height: 86.h,
          decoration: BoxDecoration(color: Colors.transparent),
          child: Center(
            child: Text(
              'Loading weather...',
              style: TextStyle(fontSize: 14.sp, color: Colors.grey.shade600),
            ),
          ),
        );
  }

  /// 构建功能按钮区域
  Widget _buildFunctionButtonsSection() {
    return [
      // 左侧按钮
      ImageResourceHelper.buildContainerImage(
            imagePath: 'assets/images/knowledge_button.png',
            width: double.infinity,
            height: 117.h,
            fit: BoxFit.fill,
            borderRadius: BorderRadius.circular(12.r),
          )
          .parent(
            ({required Widget child}) =>
                AspectRatio(aspectRatio: 167 / 117, child: child),
          )
          .inkWell(onTap: _onKnowledgeButtonTapped)
          .expanded(),
      // 右侧按钮
      ImageResourceHelper.buildContainerImage(
            imagePath: 'assets/images/tutorial_button.png',
            width: double.infinity,
            height: 117.h,
            fit: BoxFit.fill,
            borderRadius: BorderRadius.circular(12.r),
          )
          .parent(
            ({required Widget child}) =>
                AspectRatio(aspectRatio: 167 / 117, child: child),
          )
          .inkWell(onTap: _onTutorialButtonTapped)
          .expanded(),
    ].toRowSpace(space: 12.w).paddingHorizontal(16.w);
  }

  /// 构建Kite Moment列表区域
  Widget _buildKiteMomentSection() {
    return [
          // 标题
          Text('Kite Moment')
              .fontSize(24.sp)
              .fontWeight(FontWeight.w900)
              .fontFamily(GoogleFonts.montserrat().fontFamily)
              .textColor(KudoColors.black),
          // GridView
          KiteMomentController.globalInstance.allMomentsState
                  .reactiveValue(context)
                  .isNotEmpty
              ? GridView.builder(
                shrinkWrap: true,
                padding: EdgeInsets.zero,
                physics: const NeverScrollableScrollPhysics(),
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  crossAxisSpacing: 12.w,
                  mainAxisSpacing: 12.h,
                  childAspectRatio: 167 / 196,
                ),
                itemCount:
                    KiteMomentController
                        .globalInstance
                        .allMomentsState
                        .value
                        .length,
                itemBuilder: (context, index) {
                  final moment =
                      KiteMomentController
                          .globalInstance
                          .allMomentsState
                          .value[index];
                  return _buildKiteMomentItem(moment);
                },
              )
              : Container(
                height: 200.h,
                decoration: BoxDecoration(
                  color: Colors.grey.shade200,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Center(
                  child: Text(
                    'No Kite Moments yet',
                    style: TextStyle(
                      fontSize: 14.sp,
                      color: Colors.grey.shade600,
                    ),
                  ),
                ),
              ),
        ]
        .toColumnSpace(
          space: 16.h,
          crossAxisAlignment: CrossAxisAlignment.start,
        )
        .paddingHorizontal(16.w);
  }

  /// 构建单个Kite Moment项目
  Widget _buildKiteMomentItem(KiteMomentEntity moment) {
    return AspectRatio(
      aspectRatio: 167 / 196,
      child: GestureDetector(
        onTap: () => _onKiteMomentItemTapped(moment),
        child: Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(10.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.1),
                blurRadius: 8,
                offset: const Offset(0, 2),
              ),
            ],
          ),
          child: ClipRRect(
            borderRadius: BorderRadius.circular(10.r),
            child: Stack(
              children: [
                // 背景图片
                _buildMomentBackground(moment),
                // 视频播放图标
                if (moment.isVideoType) _buildVideoPlayIcon(),
                // 顶部用户信息和举报按钮
                _buildMomentTopOverlay(moment),
                // 底部内容文字
                _buildMomentBottomOverlay(moment),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建Moment背景图片
  Widget _buildMomentBackground(KiteMomentEntity moment) {
    String imagePath;
    if (moment.isVideoType) {
      imagePath =
          moment.thumbnailResourceUrl?.isNotEmpty == true
              ? moment.thumbnailResourceUrl!
              : moment.displayThumbnailUrl;
    } else {
      imagePath = moment.mediaResourceUrl;
    }

    return ImageResourceHelper.buildImageWidget(
      imagePath: imagePath,
      width: double.infinity,
      height: double.infinity,
      fit: BoxFit.cover,
    );
  }

  /// 构建视频播放图标
  Widget _buildVideoPlayIcon() {
    return Center(
      child: Icon(Icons.play_arrow, color: Colors.white, size: 38.sp),
    );
  }

  /// 构建顶部用户信息和举报按钮覆盖层
  Widget _buildMomentTopOverlay(KiteMomentEntity moment) {
    return [
          // 用户头像和用户名
          [
            _buildAuthorAvatar(moment.authorIdentifier),
            _buildAuthorName(moment.authorIdentifier).expanded(),
          ].toRowSpace(space: 6.w).expanded(),
          // 举报按钮
          ImageResourceHelper.buildSvgIcon(
            svgPath: 'assets/svg/report.svg',
            width: 20.w,
            height: 20.h,
            color: Colors.white,
          ).inkWell(onTap: () => _showMomentReportDialog(moment)),
        ]
        .toRow()
        .parent(
          ({required Widget child}) =>
              Padding(padding: EdgeInsets.all(8.w), child: child),
        )
        .parent(
          ({required Widget child}) => Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [
                  Colors.black.withValues(alpha: 0.6),
                  Colors.transparent,
                ],
              ),
            ),
            child: child,
          ),
        )
        .positioned(top: 0, left: 0, right: 0);
  }

  /// 构建底部内容文字覆盖层
  Widget _buildMomentBottomOverlay(KiteMomentEntity moment) {
    return Positioned(
      bottom: 0,
      left: 0,
      right: 0,
      child: Container(
        padding: EdgeInsets.all(8.w),
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.bottomCenter,
            end: Alignment.topCenter,
            colors: [Colors.black.withValues(alpha: 1), Colors.transparent],
          ),
        ),
        child: Text(
          moment.contentText,
          style: TextStyle(
            fontSize: 12.sp,
            color: Colors.white,
            fontFamily: GoogleFonts.lato().fontFamily,
            fontWeight: FontWeight.w600,
          ),
          maxLines: 2,
          overflow: TextOverflow.ellipsis,
        ),
      ),
    );
  }

  /// 构建作者头像
  Widget _buildAuthorAvatar(String authorId) {
    final users = PersonaEntity.getDefaultKiteUsers();
    final user = users.firstWhere(
      (u) => u.uniqueIdentifier == authorId,
      orElse: () => users.first,
    );
    return ImageResourceHelper.buildCircularAvatar(
      imagePath: user.avatarResourceUrl,
      radius: 14.r,
    );
  }

  /// 构建作者用户名
  Widget _buildAuthorName(String authorId) {
    final users = PersonaEntity.getDefaultKiteUsers();
    final user = users.firstWhere(
      (u) => u.uniqueIdentifier == authorId,
      orElse: () => users.first,
    );
    return Text(
      user.displayAlias,
      style: TextStyle(
        fontSize: 12.sp,
        color: Colors.white,
        fontWeight: FontWeight.w600,
        fontFamily: GoogleFonts.lato().fontFamily,
        fontStyle: FontStyle.italic,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  /// 显示Moment举报弹窗
  void _showMomentReportDialog(KiteMomentEntity moment) {
    ReportDialog.show(
      context: context,
      title: 'Report Kite Moment',
      onReport: (reportType) {
        // 删除被举报的Moment
        final success = KiteMomentController.globalInstance.deleteKiteMoment(
          moment.uniqueIdentifier,
        );
        if (success) {
          KudoToast.showSuccessToast(context, 'Reported successfully.');
        } else {
          KudoToast.showErrorToast(context, 'Failed to report Kite Moment');
        }
      },
    );
  }

  /// 功能按钮点击事件 - 导航到风筝文化页面
  void _onKnowledgeButtonTapped() {
    AppNavigationManager.navigateToKiteCulture(context);
  }

  /// 功能按钮点击事件 - 导航到风筝教程页面
  void _onTutorialButtonTapped() {
    AppNavigationManager.navigateToKiteTutorial(context);
  }

  /// 风筝时刻项点击事件 - 导航到详情页面
  void _onKiteMomentItemTapped(KiteMomentEntity moment) {
    AppNavigationManager.navigateToKiteMomentDetail(context, moment);
  }

  /// 编辑按钮点击事件 - 导航到发布页面
  void _handleEditButtonTap() {
    AppNavigationManager.navigateToReleaseScreen(context);
  }
}
